package com.jxauaia.contest.controller;

import com.jxauaia.contest.common.response.Result;
import com.jxauaia.contest.model.dto.UserProfileDTO;
import com.jxauaia.contest.model.entity.User;
import com.jxauaia.contest.service.FileService;
import com.jxauaia.contest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/avatars")
public class AvatarController {

    private final FileService fileService;
    private final UserService userService;

    @Autowired
    public AvatarController(FileService fileService, UserService userService) {
        this.fileService = fileService;
        this.userService = userService;
    }

    /**
     * 获取所有可用的系统头像
     */
    @GetMapping("/list")
    public Result<List<String>> getAllAvatars() {
        List<String> avatars = fileService.getAllAvatars();
        return Result.success(avatars);
    }

    /**
     * 设置用户选择的头像
     */
    @PostMapping("/select")
    public Result<String> selectAvatar(@RequestBody Map<String, String> request) {
        String avatarUrl = request.get("avatarUrl");
        
        if (avatarUrl == null || avatarUrl.isEmpty()) {
            return Result.error(400, "头像URL不能为空");
        }
        
        // 验证头像URL是否在系统提供的头像列表中
        List<String> availableAvatars = fileService.getAllAvatars();
        if (!availableAvatars.contains(avatarUrl)) {
            return Result.error(400, "无效的头像URL");
        }
        
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username);
        
        if (currentUser == null) {
            return Result.error(404, "用户不存在");
        }
        
        // 更新用户头像
        UserProfileDTO userProfileDTO = new UserProfileDTO();
        userProfileDTO.setAvatar(avatarUrl);
        userService.updateUserProfile(currentUser.getId(), userProfileDTO);
        
        return Result.success("头像设置成功", avatarUrl);
    }
}